package cn.itcast.n4_共享模型_管程;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

import static cn.itcast.util.Sleeper.sleep;

@Slf4j(topic = "c.Test45_ReentrantLock_使用条件变量解决有烟干活有外卖干活")
public class Test45_ReentrantLock_使用条件变量解决有烟干活有外卖干活 {
    static final ReentrantLock room = new ReentrantLock();
    static boolean hasCigarette = false;
    static boolean hasTakeout = false;
    static Condition waitCigaretteSet = room.newCondition();//等待烟的休息室
    static Condition waitTakeoutSet = room.newCondition();//等外卖的休息室

    /**
     * notify有可能唤醒错误---虚假唤醒
     * @param args
     */
    public static void main(String[] args) {

        // 等待烟线程
        new Thread(() -> {
            room.lock();
            try {
                log.debug("有烟没？[{}]", hasCigarette);
                while (!hasCigarette) {
                    log.debug("没烟，先歇会！");
                    try {
                        waitCigaretteSet.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.debug("有烟没？[{}]", hasCigarette);
                if (hasCigarette) {
                    log.debug("可以开始干活了");
                } else {
                    log.debug("没干成活...");
                }
            }finally {
                room.unlock();
            }
        }, "小南").start();

        // 等待外卖线程
        new Thread(() -> {
            room.lock();
            try {
                log.debug("外卖送到没？[{}]", hasTakeout);
                if (!hasTakeout) {
                    log.debug("没外卖，先歇会！");
                    try {
                        waitTakeoutSet.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.debug("外卖送到没？[{}]", hasTakeout);
                if (hasTakeout) {
                    log.debug("可以开始干活了");
                } else {
                    log.debug("没干成活...");
                }
            }finally {
                room.unlock();
            }
        }, "小女").start();

        sleep(1);
        new Thread(() -> {
            room.lock();
            try {
                hasTakeout = true;
                log.debug("外卖到了噢！");
                waitTakeoutSet.signalAll();
            }finally {
                room.unlock();
            }
        }, "送外卖的").start();

        sleep(1);

        new Thread(() -> {
            room.lock();
            try {
                hasCigarette = true;
                log.debug("烟到了噢！");
                waitCigaretteSet.signalAll();
            }finally {
                room.unlock();
            }
        }, "送烟的").start();

    }
}
